package logic

import (
	"context"

	"gb28181/gb28181"
	"gb28181/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListDevicesLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListDevicesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListDevicesLogic {
	return &ListDevicesLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListDevicesLogic) ListDevices(in *gb28181.DeviceListRequest) (*gb28181.DeviceListResponse, error) {
	// 获取设备列表
	devices := l.svcCtx.ClientMgr.ListDevices()
	
	// 分页处理
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}
	
	start := (page - 1) * pageSize
	end := start + pageSize
	if end > int32(len(devices)) {
		end = int32(len(devices))
	}
	
	if start >= int32(len(devices)) {
		return &gb28181.DeviceListResponse{
			Devices: []*gb28181.DeviceInfo{},
			Total:   int32(len(devices)),
		}, nil
	}
	
	// 构建响应
	var deviceInfos []*gb28181.DeviceInfo
	for i := start; i < end; i++ {
		device := devices[i]
		status := "离线"
		if device.IsOnline() {
			status = "在线"
		}
		
		deviceInfos = append(deviceInfos, &gb28181.DeviceInfo{
			DeviceId:      device.DeviceId,
			SipUri:        device.SipUri,
			Status:        status,
			LastHeartbeat: device.LastHeartbeat.Format("2006-01-02 15:04:05"),
		})
	}
	
	return &gb28181.DeviceListResponse{
		Devices: deviceInfos,
		Total:   int32(len(devices)),
	}, nil
}
